package fr.norsys.mapper.console.service;

import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.beanutils.BeanUtils;

import uk.ltd.getahead.dwr.ExecutionContext;
import fr.norsys.mapper.console.exception.AttributeException;
import fr.norsys.mapper.console.model.Attribute;
import fr.norsys.mapper.console.model.ConsoleCst;
import fr.norsys.mapper.console.model.Resource;
import fr.norsys.mapper.console.utils.UIDGenerator;

public class AttributeServiceImpl implements AttributeService  {
	
	AttributeServiceImpl(){
		super();
	}

	/**
	 * Service to get an attribute from its resource, by its id
	 * @param currentAttribute
	 * @param resource
	 * @return
	 */
	public Attribute get(String currentAttrId, Resource resource){
		Attribute attribute=null;
		Collection attributes = resource.getAttributes();
		for(Iterator it=attributes.iterator();it.hasNext();){
			
			Attribute a = (Attribute)it.next();
			if(a.getId().equals(currentAttrId)){
				attribute=a;
			}
		}
		
		return attribute;
	}

	/**
	 * Action to save (modify or add) the current attribute 
	 * for the application in seession.
	 * @param attribute (Attribute) : the current attribute of the resource
	 * @param resource (Resource) : the current resource
	 * @throws Exception 
	 */
	public void save(Attribute attribute, Resource resource) throws AttributeException{
		if(attribute.getId()!=null && attribute.getId().length()>0){
			modify(attribute,resource);
		}else{
			add(attribute,resource);
		}
	}

	/**
	 * action to add an attribute in session
	 * 
	 * @param attribute :
	 *            bean of the attribute
	 * @param resource :
	 *            bean of the resource
	 * @throws Exception 
	 */
	private void add(Attribute attribute, Resource resource) throws AttributeException {
		Attribute a = null;
		try {
			a = (Attribute) BeanUtils.cloneBean(attribute);
		} catch (Exception e) {
			throw new AttributeException (e.toString());
		}
		a.setId(UIDGenerator.generateId());
		resource.getAttributes().add(a);
		ExecutionContext.get().getSession().setAttribute(ConsoleCst.CURRENT_ATTRIBUTE,a);
	}

	/**
	 * action to modify an attribute in session
	 * 
	 * @param attribute :
	 *            bean of the attribute
	 * @param resource :
	 *            bean of the resource
	 */
	private void modify(Attribute attr, Resource resource) {
		Attribute currentAttribute = attr;
		Attribute a = get(currentAttribute.getId(), resource);
		fr.norsys.mapper.console.utils.BeanUtils.copyFilledProperties(a, currentAttribute);
		currentAttribute = a;
		ExecutionContext.get().getSession().setAttribute(ConsoleCst.CURRENT_ATTRIBUTE,currentAttribute);
	}
}
